package com.weather.androidweather.util;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GeocodingHelper {
    private static final String TAG = "GeocodingHelper";
    private static final String API_KEY = "DithqIoI8UIBN9h79Zl55aRy56fJR9Iy";
    private static final String BASE_URL = "https://api.map.baidu.com/reverse_geocoding/v3/";

    private static final double X_PI = Math.PI * 3000.0 / 180.0;
    private static final double a = 6378245.0;
    private static final double ee = 0.00669342162296594323;

    private Handler mainHandler;

    public interface GeocodingCallback {
        void onSuccess(String city);
        void onFailed(String error);
    }

    public GeocodingHelper() {
        mainHandler = new Handler(Looper.getMainLooper());
    }

    // WGS84转百度坐标系(BD09)
    private double[] wgs84ToBd09(double lng, double lat) {
        double[] gcj = wgs84ToGcj02(lng, lat);
        double[] bd = gcj02ToBd09(gcj[0], gcj[1]);
        return bd;
    }

    // WGS84转GCJ02
    private double[] wgs84ToGcj02(double lng, double lat) {
        if (outOfChina(lng, lat)) {
            return new double[]{lng, lat};
        }
        double dLat = transformLat(lng - 105.0, lat - 35.0);
        double dLng = transformLng(lng - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * Math.PI;
        double magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
        dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI);
        double mgLat = lat + dLat;
        double mgLng = lng + dLng;
        return new double[]{mgLng, mgLat};
    }

    // GCJ02转百度坐标系(BD09)
    private double[] gcj02ToBd09(double lng, double lat) {
        double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * X_PI);
        double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * X_PI);
        double bdLng = z * Math.cos(theta) + 0.0065;
        double bdLat = z * Math.sin(theta) + 0.006;
        return new double[]{bdLng, bdLat};
    }

    // 判断是否在中国境内
    private boolean outOfChina(double lng, double lat) {
        return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
    }

    // 转换纬度
    private double transformLat(double x, double y) {
        double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y +
                0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 *
                Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * Math.PI) + 40.0 *
                Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 *
                Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    // 转换经度
    private double transformLng(double x, double y) {
        double ret = 300.0 + x + 2.0 * y + 0.1 * x * x +
                0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 *
                Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * Math.PI) + 40.0 *
                Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 *
                Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
        return ret;
    }

    public void getCityFromLocation(final double latitude, final double longitude, final GeocodingCallback callback) {
        new Thread(() -> {
            try {
                // 构建请求URL
                StringBuilder urlBuilder = new StringBuilder(BASE_URL);
                urlBuilder.append("?ak=").append(API_KEY);
                urlBuilder.append("&output=json");
                urlBuilder.append("&coordtype=bd09ll");
                urlBuilder.append("&extensions_poi=1");
                urlBuilder.append("&location=").append(latitude).append(",").append(longitude);
                urlBuilder.append("&language=zh-CN");

                String urlString = urlBuilder.toString();
                Log.d(TAG, "请求URL: " + urlString);

                URL url = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();

                    Log.d(TAG, "API响应: " + response.toString());

                    JSONObject jsonResponse = new JSONObject(response.toString());
                    if (jsonResponse.getInt("status") == 0) {
                        JSONObject result = jsonResponse.getJSONObject("result");
                        JSONObject addressComponent = result.getJSONObject("addressComponent");
                        String city = addressComponent.getString("city");
                        
                        // 如果city为空，可能是县级市，尝试使用district
                        if (city == null || city.isEmpty()) {
                            city = addressComponent.getString("district");
                        }
                        
                        // 如果仍然为空，使用province
                        if (city == null || city.isEmpty()) {
                            city = addressComponent.getString("province");
                        }

                        // 移除"市"、"区"、"县"等后缀
                        if (city != null && !city.isEmpty()) {
                            city = city.replace("市", "")
                                     .replace("区", "")
                                     .replace("县", "")
                                     .replace("自治州", "")
                                     .replace("特别行政区", "");
                        }

                        if (city != null && !city.isEmpty()) {
                            callback.onSuccess(city);
                        } else {
                            callback.onFailed("无法获取城市信息");
                        }
                    } else {
                        callback.onFailed("API返回错误: " + jsonResponse.getInt("status"));
                    }
                } else {
                    callback.onFailed("HTTP请求失败: " + connection.getResponseCode());
                }
            } catch (Exception e) {
                Log.e(TAG, "地理编码失败", e);
                callback.onFailed("地理编码失败: " + e.getMessage());
            }
        }).start();
    }
} 